Java Static and Dynamic binding

    Static and Dynamic binding

    The process of connecting the method call to the body of the method is called binding. There are two types of binding-

    • Static binding (early binding)
    • Dynamic binding (late binding)

    Static binding is the binding where the object type will get determined at the compile time. Dynamic binding is the binding where the object type is determined at the runtime.

    Determining the type-

    • Variables can have a type either primitive or non-primitive.

    Example- float var=34.5;

    In the above example, the var variable is of float type.

    • A reference has the type of class.

    Example-

    class demo{
     public static void main(String args[]){  
    
    demo d;
    
    }}

    In the above example, we create a reference (d) of the class demo type.

    • An object refers to its class and also the parent class.

    Example-

    class parent{
    
    Int var=100;}
    
    class demo extends parent{
    
     public static void main(String args[]){  
    
    demo d= new demo;
    
    }}

    In the above example, we create an object d that is an instance of demo type and also of the parent type.

    Static binding example-

    Example-

    class Demo{  
    
    int var=100;
    
    //class Child_demo extends Child{  
    // int var=30;
      
    
      public static void main(String args[]){  
    
        Demo b = new Demo();
    
        System.out.println(b.var);  
    
      }  
    
    }  

    Output-

    100

    Dynamic binding example-

    Example-

    class Simple{  
    
    int var=100;}
    
    
    
    class Child_Simple extends Simple{  
    
     int var=30;
    
      
    
      public static void main(String args[]){  
    
        Simple b = new Child_Simple();  
    
        System.out.println(b.var);  
    
      }  
    
    }  

    Output-

    100